package easier.sectionheader.decoration;

import android.widget.SectionIndexer;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;

/**
 * 管理数据及其数据生成的索引
 */
public abstract class SectionDataIndexer< E > implements SectionIndexer {

    protected List< E > mData;
    protected String[] mSection;

    public SectionDataIndexer( List< E > data ) {

        mData = data;
        mSection = createSections( data );
    }

    @Override
    public String[] getSections() {

        return mSection;
    }

    @Override
    public int getPositionForSection( int sectionIndex ) {

        if ( mSection == null || mData == null ) {
            return RecyclerView.NO_POSITION;
        }
        if ( sectionIndex < 0 || sectionIndex >= mSection.length ) {
            return RecyclerView.NO_POSITION;
        }

        String section = mSection[sectionIndex];
        for ( int i = 0; i < mData.size(); i++ ) {
            E data = mData.get( i );
            if ( sectionEquals( data, section ) ) {
                return i;
            }
        }
        return RecyclerView.NO_POSITION;
    }

    @Override
    public int getSectionForPosition( int position ) {

        if ( mData == null || mSection == null ) {
            return -1;
        }

        if ( position < 0 || position >= mData.size() ) {
            return -1;
        }

        E data = mData.get( position );
        for ( int i = 0; i < mSection.length; i++ ) {
            String section = mSection[i];
            if ( sectionEquals( data, section ) ) {
                return i;
            }
        }
        return -1;
    }

    /**
     * 判断数据与索引是否一一对应
     *
     * @param e       数据
     * @param section 索引
     *
     * @return true:数据与索引对应
     */
    protected abstract boolean sectionEquals( E e, String section );

    /**
     * 为数据创建索引
     *
     * @param source 数据
     *
     * @return 索引
     */
    protected abstract String[] createSections( List< E > source );
}